package edu.whu.assignment5.controller;

import edu.whu.assignment5.dataobject.Product;
import edu.whu.assignment5.dataobject.ReturnObj;
import edu.whu.assignment5.dataobject.Supplier;
import edu.whu.assignment5.enums.ReturnEnums;
import edu.whu.assignment5.service.SupplierService;
import edu.whu.assignment5.util.ReturnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    @GetMapping("/{sid}")
    public ReturnObj findById(@PathVariable int sid) {
        if(sid <= 0) {
            return ReturnUtil.error(ReturnEnums.ParamError);
        }
        Supplier result = supplierService.findById(sid);
        if(result == null) {
            return ReturnUtil.error(ReturnEnums.DataNotFound);
        }
        else {
            return ReturnUtil.success(result);
        }
    }

    @PostMapping("")
    public ReturnObj addSupplier(String sname, Integer pid) {
        System.out.println(pid);
        if(sname == null || sname.equals("") || pid <= 0) {
            return ReturnUtil.error(ReturnEnums.ParamError);
        }
        int result = supplierService.addSupplier(sname, pid);
        if(result == -1) {
            return ReturnUtil.error(ReturnEnums.NoProduct);
        }
        else if(result == 1){
            return ReturnUtil.success();
        }
        else {
            return ReturnUtil.error(ReturnEnums.DataSaveError);
        }
    }

    @DeleteMapping("/{sid}")
    public ReturnObj deleteById(@PathVariable int sid) {
        if(sid <= 0) {
            return ReturnUtil.error(ReturnEnums.ParamError);
        }
        int result = supplierService.deleteSupplier(sid);
        if(result == 1) {
            return ReturnUtil.success();
        }
        else {
            return ReturnUtil.error(ReturnEnums.DataSaveError);
        }
    }
}
